﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Microsoft.VisualBasic;

using Google.Apis;
using Google.Apis.Util;
using Google.Apis.Samples.Helper;
using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Oauth2.v2;
using Google.Apis.Tasks.v1;
using Google.Apis.Tasks.v1.Data;
using GoogleTasksMigrator.Custom.Extensions;

namespace GoogleTasksMigrator
{
    public partial class Form1 : Form
    {
        BiBiCyGTasksManager bibicy= null;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Enable Exception Handling
            AppDomain.CurrentDomain.UnhandledException += HandleUnhandledException;
            bibicy=new BiBiCyGTasksManager();
        }

        private void HandleUnhandledException(object sender, UnhandledExceptionEventArgs args)
        {
            Exception exception = args.ExceptionObject as Exception;

            // Display the exception
            LogLine();
            LogLine(" ^6Exception non gérée :");
            LogLine(String.Format("    ^6{0}", exception == null ? "<error inconnue>" : exception.Message));
            LogLine();
            LogLine(String.Format(" ^1{0}", exception));
        }

        private void btnSrcCnx_Click(object sender, EventArgs e)
        {
            try
            {
                bibicy.Src.Connect();
                lbSrcStatus.Text = bibicy.Src.Email;
                btnSrcCnx.Enabled = false;
                btnCopy.Enabled = true;
                DumpTasksLists(bibicy.Src, rtbSrcLists);
            }
            catch (Exception ex)
            {
                LogLine("---");
                LogLine(String.Format("!! ERREUR :{0} !!", ex.Message));
                LogLine("---");
            }
        }

        private void btnDstCnx_Click(object sender, EventArgs e)
        {
            try
            {
                bibicy.Dest.Connect();
                lbDstStatus.Text = bibicy.Dest.Email;
                btnDstCnx.Enabled = false;
                btnDstRAZ.Enabled = true;
                DumpTasksLists(bibicy.Dest, rtbDstLists);
            }
            catch (Exception ex)
            {
                LogLine("---");
                LogLine(String.Format("!! ERREUR :{0} !!", ex.Message));
                LogLine("---");
            }
        }

        private void DumpTasksLists(GTasksManager tasks_mgr, RichTextBox rtbHolder)
        {
            Tasks tasks = null;

            rtbHolder.Text = "";
            foreach (TaskList list in tasks_mgr.TaskLists.Items)
            {
                tasks = tasks_mgr.GetTasks(list.Id);
                rtbHolder.AppendText(String.Format("- {0} ({1} tâches)", list.Title, (tasks.Items==null ? 0 : tasks.Items.Count)));
                rtbHolder.AppendText(Environment.NewLine);
            }
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            foreach (TaskList list in bibicy.Src.TaskLists.Items)
            {   // todo: only selected task lists
                try
                {
                    TaskList new_list = bibicy.CopyTaskList(list);
                    LogLine(String.Format("COPY List '{0}' OK", new_list.Title));
                }
                catch (Exception ex)
                {
                    LogLine(String.Format("!! ERR while copying list '{0}' : {1}", list.Title, ex.Message));
                }
                finally
                {
                    foreach (Task task in bibicy.Src.GetTasks(list.Id).Items)
                    {   // todo: only selected tasks
                        try
                        {
                            Task new_task = bibicy.CopyTask(task, list.Id);
                            LogLine(String.Format("COPY Task '{0}' OK", new_task.Title));
                        }
                        catch (Exception ex)
                        {
                            LogLine(String.Format("!! ERR while copying task '{0}' : {1}", task.Title, ex.Message));
                        }
                    }
                }

            }
            LogLine("---");
            LogLine(String.Format("---{1}Getting taskLists for {0}...", bibicy.Dest.Email));
            DumpTasksLists(bibicy.Dest, rtbDstLists);
        }

        private void btnDstRAZ_Click(object sender, EventArgs e)
        {
            TaskLists lists = bibicy.Dest.TaskLists;
            int nb_lists = lists.Items.Count;
            string prompt = String.Format("Voulez-vous supprimer {0} listes de tâches ?", nb_lists);

            if (Interaction.MsgBox(prompt, MsgBoxStyle.OkCancel, "sûr ?") == MsgBoxResult.Ok)
            {
                foreach (TaskList l in lists.Items)
                {
                    try{
                        bibicy.Dest.DeleteList(l.Id);
                        LogLine(String.Format("DELETED list {0}", l.Title));
                    } catch(Exception ex){
                        LogLine(String.Format("!! ERROR deleting list {0} : '{1}'", l.Title, ex.Message));
                        LogLine();
                        LogLine("   -> If this is your default list, it cannot be deleted.");
                        LogLine();

                    }
                }
            }
            LogLine(String.Format("Getting taskLists for {0}...", bibicy.Dest.Email));
            DumpTasksLists(bibicy.Dest, rtbDstLists);
        }

        private void LogLine(String src="")
        {
            rtbLogs.AppendText(src + Environment.NewLine);
            rtbLogs.ScrollToCaret();
        }

    }
}
